package com.quectel.cms.controller.village;


import cn.hutool.core.collection.ListUtil;
import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.util.SessionHolder;
import com.quectel.constant.core.room.GroupRentingRoomConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.log.annotation.Log;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.household.service.HouseholdRoomService;
import com.quectel.core.module.village.dto.VillageBuildingDto;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.dto.VillageFloorDto;
import com.quectel.core.module.village.dto.VillageRoomDto;
import com.quectel.core.module.village.service.VillageBuildingService;
import com.quectel.core.module.village.service.VillageFloorService;
import com.quectel.core.module.village.service.VillageRoomService;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.POIUtils;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2021-10-18 14:41:47
 */
@RestController
@RequestMapping("villageRoom")
@Tag(name = "VillageRoomController", description = "房间相关api")
public class VillageRoomController extends BaseController {

    @DubboReference
    private VillageRoomService villageRoomService;
    @DubboReference
    private VillageService villageService;
    @DubboReference
    private VillageBuildingService villageBuildingService;
    @DubboReference
    private VillageFloorService villageFloorService;
    @DubboReference
    private HouseholdRoomService householdRoomService;

    @PostMapping("importExcel")
    @RequirePermissions(values = "villageRoom:importExcel")
    @Operation(summary = "用excel导入房屋信息")
    @Log(express = "导入房屋信息")
    public Response<Object> importExcel(
            MultipartHttpServletRequest request
    ) {
        final Long tenantId = SessionHolder.getSysUser().getTenantId();
        Date currentDate = new Date();
        int totalCount = 0;
        int successCount = 0;

        List<VillageRoomDto> villageRoomDtoList = new ArrayList<>();
        Iterator<String> fileNames = request.getFileNames();
        while (fileNames.hasNext()) {
            String next = fileNames.next();
            List<MultipartFile> files = request.getFiles(next);
            for (MultipartFile file : files) {
                try {
                    List<Map<Integer, String>> analysis = POIUtils.analysis(file.getInputStream(), 1, 0);
                    totalCount += analysis.size();

                    Map<String, List<Map<Integer, String>>> groupByParkCode = analysis.stream().collect(Collectors.groupingBy(o -> o.get(0)));
                    for (String villageName : groupByParkCode.keySet()) {
                        VillageDto villageDto = villageService.selectCacheByName(tenantId, villageName);
                        if (villageDto == null) {
                            continue;
                        }

                        List<Map<Integer, String>> maps = groupByParkCode.get(villageName);
                        List<VillageRoomDto> roomList = maps.stream().map(row -> {
                            String buildingName = row.get(1);
                            String floorNo = row.get(2);
                            String roomName = row.get(3);
                            String area = row.get(4);
                            String roomNature = row.get(5);
                            String roomStatus = row.get(6);
                            String roomType = row.get(7);
                            String ownerName = row.get(8);
                            String ownerMobile = row.get(9);

                            VillageBuildingDto villageBuildingDto = villageBuildingService.selectByName(villageDto.getId(), buildingName);
                            if (villageBuildingDto == null) {
                                return null;
                            }
                            VillageFloorDto villageFloorDto = villageFloorService.selectByFloorNo(villageBuildingDto.getId(), Integer.valueOf(floorNo));
                            if (villageFloorDto == null) {
                                return null;
                            }
                            VillageRoomDto oldRoom = villageRoomService.selectByName(villageFloorDto.getId(), roomName);
                            if (oldRoom != null) {
                                return null;
                            }

                            VillageRoomDto villageRoomDto = new VillageRoomDto();
                            villageRoomDto.setTenantId(tenantId);
                            villageRoomDto.setVillageId(villageDto.getId());
                            villageRoomDto.setBuildingId(villageBuildingDto.getId());
                            villageRoomDto.setFloorId(villageFloorDto.getId());
                            villageRoomDto.setName(roomName);
                            villageRoomDto.setRoomArea(new BigDecimal(area));
                            villageRoomDto.setRoomNature(SysCodeUtils.easyToGetValue(SysCodeKeyConstants.ROOM_NATURE, roomNature, Byte.class));
                            villageRoomDto.setRoomUsage(SysCodeUtils.easyToGetValue(SysCodeKeyConstants.ROOM_USAGE, roomStatus, Byte.class));
                            villageRoomDto.setRoomType(SysCodeUtils.easyToGetValue(SysCodeKeyConstants.ROOM_TYPE, roomType, Byte.class));
                            villageRoomDto.setOwnerName(ownerName);
                            villageRoomDto.setOwnerMobile(ownerMobile);
                            villageRoomDto.setCreateTime(currentDate);
                            villageRoomDto.setCreator(SessionHolder.getSysUser().getAccount());
                            return villageRoomDto;
                        }).filter(o -> o != null).collect(Collectors.toList());

                        villageRoomDtoList.addAll(roomList);
                    }
                } catch (Exception e) {
                    logger.error("解析房源信息出错");
                }
            }
        }
        villageRoomService.saveBatch(villageRoomDtoList);
        successCount = villageRoomDtoList.size();
        return Response.error("导入数据完成 总数:" + totalCount + " 成功数:" + successCount);
    }

    /**
     * 根据楼层筛选房屋
     */
    @GetMapping("queryByFloorId")
    @Operation(summary = "根据楼层筛选房屋")
    public Response<List<VillageRoomDto>> queryByFloorId(
            @Parameter(description = "楼层") @RequestParam Long floorId
    ) {

        return Response.<List<VillageRoomDto>>ok().wrap(villageRoomService.selectByFloorId(floorId));
    }

    /**
     * 根据楼栋筛选房间
     */
    @GetMapping("queryByBuildingId")
    @Operation(summary = "根据楼栋筛选房间")
    public Response<List<VillageRoomDto>> queryByBuildingId(
            @Parameter(description = "楼栋") @RequestParam Long buildingId
    ) {

        return Response.<List<VillageRoomDto>>ok().wrap(villageRoomService.selectByBuildingId(buildingId));
    }

    /**
     * 导出房屋信息为excel
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "villageRoom:exportExcel")
    @Log(express = "导出房屋信息")
    @Operation(summary = "导出房屋信息为excel")
    public void exportExcel(@RequestParam Map<String, Object> params, HttpServletResponse hresp) {
        Request request = Request.configParamsNotPage(params);

        super.fillAuthorityData(params);

        List<VillageRoomDto> result = new ArrayList<>();
        int pageNo = 0;
        params.put("limit", 1000);
        while (true) {
            params.put("offset", pageNo++ * 1000);
            List<VillageRoomDto> list = villageRoomService.queryList(params);
            if (org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
                break;
            }
            result.addAll(list);
            if (list.size() < 1000) {
                break;
            }
        }
        String[] headers = new String[]{"所属小区", "所属楼栋", "所属楼层", "房屋名称", "房屋性质", "房屋户型", "房屋用途", "房屋面积", "业主姓名", "业主电话"};
        List<String[]> dataList = new ArrayList<>();
        for (VillageRoomDto data : result) {
            String[] item = new String[headers.length];
            item[0] = data.getVillageName();
            item[1] = data.getBuildingName();
            item[2] = data.getFloorName();
            item[3] = data.getName();
            item[4] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.ROOM_NATURE, data.getRoomNature() + "");
            item[5] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.ROOM_TYPE, data.getRoomType() + "");
            item[6] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.ROOM_USAGE, data.getRoomUsage() + "");
            item[7] = data.getRoomArea() != null ? data.getRoomArea().toPlainString() : null;
            item[8] = data.getOwnerName();
            item[9] = data.getOwnerMobile();
            dataList.add(item);
        }
        POIUtils.exportExcel(hresp, "房屋信息", headers, dataList, "房屋信息");
    }

    /**
     * 根据参数分页查询列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "villageRoom:list")
    @Operation(summary = "根据参数分页查询小区房屋列表")
    public Response<Page<VillageRoomDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        if (request.isNotBlank(GroupRentingRoomConstants.SEARCH_KEYS_STRING)) {
            request.put(GroupRentingRoomConstants.TAG_KEYS, ListUtil.toList(request.getString(GroupRentingRoomConstants.SEARCH_KEYS_STRING).split(",")));
        }

        super.fillAuthorityData(request.getParams());
        int total = villageRoomService.queryTotal(request.getParams());

        List<VillageRoomDto> list = null;
        if (total > 0) {
            list = villageRoomService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<VillageRoomDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<VillageRoomDto>>ok().wrap(page);
    }


    /**
     * 根据id查询小区房屋单条记录
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "villageRoom:info")
    @Operation(summary = "根据id查询小区房屋单条记录")
    public Response<VillageRoomDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (villageRoomService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }


        VillageRoomDto villageRoomDto = villageRoomService.selectById(id);

        return Response.<VillageRoomDto>ok().wrap(villageRoomDto);
    }

    /**
     * 保存小区房屋单条记录
     */
    @PostMapping("save")
    @RequirePermissions(values = "villageRoom:edit")
    @Operation(summary = "保存小区房屋单条记录")
    @Log(express = "保存房屋")
    public Response<Object> save(@RequestBody @Validated VillageRoomDto villageRoomDto) {
        VillageRoomDto dbValue = villageRoomService.selectByName(villageRoomDto.getFloorId(), villageRoomDto.getName());
        if (dbValue != null) {
            return Response.error("该房间已存在");
        }
        //填充基础数据
        fillSaveCommonData(villageRoomDto);

        villageRoomService.save(villageRoomDto);

        return Response.ok();
    }

    /**
     * 修改小区房屋单条记录
     */
    @PostMapping("update")
    @RequirePermissions(values = "villageRoom:edit")
    @Operation(summary = "修改小区房屋单条记录")
    @Log(express = "编辑房屋")
    public Response<Object> update(@RequestBody @Validated VillageRoomDto villageRoomDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(villageRoomDto.getId()));
        if (villageRoomService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        VillageRoomDto dbValue = villageRoomService.selectByName(villageRoomDto.getFloorId(), villageRoomDto.getName());
        if (dbValue != null && !Objects.equals(dbValue.getId(), villageRoomDto.getId())) {
            return Response.error("该房间已存在");
        }
        //填充基础数据
        fillEditCommonData(villageRoomDto);

        villageRoomService.updateById(villageRoomDto);

        return Response.ok();
    }

    /**
     * 批量删除小区房屋记录
     */
    @PostMapping("delete")
    @RequirePermissions(values = "villageRoom:delete")
    @Operation(summary = "批量删除小区房屋记录")
    @Log(express = "删除房屋")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (villageRoomService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        for (Long id : ids) {
            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put("roomId", String.valueOf(id));
            if (householdRoomService.queryTotal(params) > 0) {
                return Response.error("请先将住户和该房间解绑,再删除房间信息");
            }
        }

        villageRoomService.deleteBatch(ids);

        return Response.ok();
    }
}
